package com.rasou.consumer;

import com.rasou.constants.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class HelloConsumer {

    private static Logger logger = LoggerFactory.getLogger(HelloConsumer.class);

    final RabbitAdmin rabbitAdmin;

    public HelloConsumer(RabbitAdmin rabbitAdmin) {
        this.rabbitAdmin = rabbitAdmin;
    }

    @RabbitListener(queues = Constant.QUEUE_NAME)
    public void handle(String message) {
        logger.info("[consumer] : " + message);
    }

    @PostConstruct
    public void postConstruct() {
        Queue queue = new Queue(Constant.QUEUE_NAME);
        Exchange exchange = new DirectExchange(Constant.EXCHANGE_NAME);
        rabbitAdmin.declareQueue(queue);
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareBinding(BindingBuilder.bind(queue)
                .to(exchange)
                .with(Constant.ROUTING_NAME)
                .noargs());
    }
}
